package com.niezhipeng.topics;

import com.niezhipeng.utils.ConnectFactoryUtils;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

public class ReceiveLogsTopic {

    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        ConnectFactoryUtils.setFactoryConfig(factory);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 声明一个主题模式交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        String queueNameA = channel.queueDeclare().getQueue();
        // queueNameA关注设备A的所有消息
        //  *（星号）只能代替一个词。
        //  # (hash) 可以替代零个或多个单词
        channel.queueBind(queueNameA, EXCHANGE_NAME, "machineA.*");
        DeliverCallback deliverCallbackA = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [queueNameA] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueNameA, true, deliverCallbackA, consumerTag -> { });


        String queueNameB = channel.queueDeclare().getQueue();
        // queueNameB关注任何设备的info消息
        //  *（星号）只能代替一个词。
        //  # (hash) 可以替代零个或多个单词
        channel.queueBind(queueNameB, EXCHANGE_NAME, "*.info");
        DeliverCallback deliverCallbackB = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [queueNameB] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueNameB, true, deliverCallbackB, consumerTag -> { });

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    }
}

